package com.tanhua.sso.interceptor;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.Sso;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**拦截登录
 *
 */
public class Freezelogin implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try
        {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null)
            {
                sb.append(str);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String phone = null;
        try {
            phone = sb.toString().substring(10,21);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Sso sso = new Sso();
        sso.setPhone(phone);
        UserThreadLocal.set(sso);
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("mobile", phone);
        User user = userMapper.selectOne(query);
        if(user!=null){
            String s = redisTemplate.opsForValue().get("Freezelogin" + user.getId());
            if(s==null){
                return true;
            }else {
                return false;
            }
        }
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removesso();
    }
}
